import { ResourceApi } from "./resource-api";
import { RuleInfo, ResourceType } from "../modules";
import { Storage } from "../Storage";

/**
 * 规则接口
 */
export class RuleApi extends Storage<RuleInfo[]> implements ResourceApi<RuleInfo[]> {


    remove(t: string): void{
        let res = this.getAll();
        let newRes: RuleInfo[] = [];
        for (let i=0; i<res.length; i++) {
            if (res[i].id != t) {
                newRes.push(res[i]);
            }
        }
        this.storageSet("RULE", newRes);
    }

    getAll(): RuleInfo[] {
       let res = this.storageGet("RULE", "[]");
       return res;
    }
    update(t: RuleInfo) {
        let res = this.getAll();
        if (t.id) {
            for (let i=0; i<res.length; i++) {
                let ele = res[i];
                if (ele.id === t.id) {
                    res[i] = Object.assign({}, t);
                }
            }
        } else {
            t.id = this.guid();
            res.push(t);
        }
        this.storageSet("RULE", res);
    }


    S4(){
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    guid(){
        return (this.S4()+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+this.S4()+this.S4());
    };

}